//
//  LCFileManager.m
//  iPhone
//
//  Created by dodo liu on 12-9-26.
//  Copyright (c) 2012年 臻昇￼科技. All rights reserved.
//

#import "LCFileManager.h"
@interface LCFileManager ()

@end
@implementation LCFileManager
@synthesize delegate;
-(void)downLoadFilesWithUrlArray:(NSArray*)urlArray 
                  UIProgressView:(UIProgressView*)progressView 
                 queueIdentifier:(NSString*)queueIdentifier 
                      saveToPath:(NSString*)path //@"Documents/products12/"
                      folderName:(NSString*)foldername //@"8"
{
    /*
     if (!networkQueue) {
     networkQueue = [[ASINetworkQueue alloc] init];	
     }
     */
    
    
    ASINetworkQueue *networkQueue = [[ASINetworkQueue alloc] init];
    [networkQueue setUserInfo:[NSDictionary dictionaryWithObject:queueIdentifier forKey:@"id"]];
	//failed = NO;
	[networkQueue reset];

    if(progressView)
	{
        [networkQueue setDownloadProgressDelegate:progressView];
    }
	[networkQueue setRequestDidFinishSelector:@selector(requestDidFinish:)];
	[networkQueue setRequestDidFailSelector:@selector(requestDidFail:)];
    [networkQueue setRequestDidReceiveResponseHeadersSelector:@selector(didReceiveResponseHeaders:)];
    [networkQueue setQueueDidFinishSelector:@selector(queueDidFinish:)];
    
	[networkQueue setShowAccurateProgress:YES];
	[networkQueue setDelegate:self];
	
    ASIHTTPRequest *request;
     
      if([self isExistsFolderAtPath:path FolderName:foldername])
          [self deleteFloderInPath:path FolderName:foldername];    
    [self createFloderInPath:path FolderName:foldername];
    for(int i=0;i<urlArray.count;i++)
    {
       // NSMutableDictionary *nd=[result_array objectAtIndex:i];
        NSString *stringurl=[urlArray objectAtIndex:i];        //根据URL地址取出文件名的后缀
        NSString *exestr = [stringurl pathExtension];
        //NSLog(@"the exestr %@",exestr);
        //拼接成原来文件名的后最
       
       // request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[nd valueForKey:@"photoUrl"]]];
        request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:stringurl]];
        
         NSString *str=[NSString stringWithFormat:@"%d.%@",i,exestr];
        NSString *fullPath=[path stringByAppendingPathComponent:foldername];
        [request setDownloadDestinationPath:[[NSHomeDirectory() stringByAppendingPathComponent:fullPath] stringByAppendingPathComponent:str]];
        //[request setDownloadProgressDelegate:imageProgressIndicator1];
        [request setUserInfo:[NSDictionary dictionaryWithObject:@"i" forKey:@"dd"]];
        
        
        [networkQueue addOperation:request];
        //APPDELE=[[UIApplication sharedApplication]delegate];
       // APPDELE.requestCount++;//请求数加一
    }
    
    [networkQueue go];
  
}

-(void)didReceiveResponseHeaders:(ASIHTTPRequest *)request
{
    NSLog(@"didReceiveResponseHeaders %@",[request.responseHeaders valueForKey:@"Content-Length"]);
}

-(void)queueDidFinish:(ASINetworkQueue*)queue
{
   [delegate queueFilish:[[queue userInfo] valueForKey:@"id"]];
   // NSLog(@"queue is finish!id =[%@]",[[queue userInfo] valueForKey:@"id"]);
    //[delegate queueFilish:[[queue userInfo] valueForKey:@"id"]];
    
}

- (void)requestDidFinish:(ASIHTTPRequest *)request
{
    
   // APPDELE=[[UIApplication sharedApplication]delegate];
   // APPDELE.requestCount--;//请求数减一
}


- (void)requestDidFail:(ASIHTTPRequest *)request
{

}
-(void)downLoadFilesWithDatalArray:(NSArray*)dataArray 
                    dictionaryKey:(NSString*)ndKey
                  UIProgressView:(UIProgressView*)progressView 
                 queueIdentifier:(NSString*)queueIdentifier 
                      saveToPath:(NSString*)path //@"Documents/products12/"
                      folderName:(NSString*)foldername //@"8"
                 //theNetworkQueue:(ASINetworkQueue*)networkQueue
{
 
    
    ASINetworkQueue *networkQueue = [[ASINetworkQueue alloc] init];
    //networkQueue = [[ASINetworkQueue alloc] init];
    [networkQueue setUserInfo:[NSDictionary dictionaryWithObject:queueIdentifier forKey:@"id"]];
	//failed = NO;
	[networkQueue reset];
    if(progressView)
	{
        [networkQueue setDownloadProgressDelegate:progressView];
    }
	//[networkQueue setRequestDidFinishSelector:@selector(imageFetchComplete:)];
//	[networkQueue setRequestDidFailSelector:@selector(imageFetchFailed:)];
    //[networkQueue setQueueDidFinishSelector:@selector(queueComplete:)];
	[networkQueue setShowAccurateProgress:YES];
	[networkQueue setDelegate:self];
	
    ASIHTTPRequest *request;
    
    
    if([self isExistsFolderAtPath:path FolderName:foldername])
        [self deleteFloderInPath:path FolderName:foldername];    
    [self createFloderInPath:path FolderName:foldername];
    for(int i=0;i<dataArray.count;i++)
    {
         NSDictionary *nd=[dataArray objectAtIndex:i];

        request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[nd valueForKey:ndKey]]];
        NSString *str=[NSString stringWithFormat:@"%d.jpg",i];
        NSString *fullPath=[path stringByAppendingPathComponent:foldername];
        [request setDownloadDestinationPath:[[NSHomeDirectory() stringByAppendingPathComponent:fullPath] stringByAppendingPathComponent:str]];
        //[request setDownloadProgressDelegate:imageProgressIndicator1];
        //[request setUserInfo:[NSDictionary dictionaryWithObject:@"request1" forKey:@"name"]];
        
        [networkQueue addOperation:request];
    }
    
    [networkQueue go];

}

//判断在Documents是否存在文件夹
- (BOOL)isExistsFolderAtDoucument:(NSString *)folde_name
{
    
    NSString *filePath =[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    
    if (folde_name != nil)
    {
        filePath = [filePath stringByAppendingPathComponent:folde_name];
        NSLog(@"%@",filePath);
    }
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath])
        return YES;
    else 
        return NO;
    
}

//判断在指定路径下是否存在文件夹
- (BOOL)isExistsFolderAtPath:(NSString*)path FolderName:(NSString*)folderName
{
    
    NSString *filePath =[NSHomeDirectory() stringByAppendingPathComponent:path];
    
    if (folderName != nil)
    {
        filePath = [filePath stringByAppendingPathComponent:folderName];
        NSLog(@"%@",filePath);
    }
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath])
        return YES;
    else 
        return NO;
    
}

//创建文件夹 正document 根目录下
- (void)createFloderInDocument:(NSString*)folderName
{
    NSString *filePath =[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    
    
    BOOL isCreate = [[NSFileManager defaultManager] createDirectoryAtPath:[filePath stringByAppendingPathComponent:folderName] withIntermediateDirectories:YES attributes:nil error:nil];
    if(isCreate)
        NSLog(@"YES");
    else {
        NSLog(@"NO");
    }
}
//创建文件夹 在指定路径下
- (void)createFloderInPath:(NSString*)path FolderName:(NSString*)folderName
{
    NSString *filePath =[NSHomeDirectory() stringByAppendingPathComponent:path];
    
    
    BOOL isCreate = [[NSFileManager defaultManager] createDirectoryAtPath:[filePath stringByAppendingPathComponent:folderName] withIntermediateDirectories:YES attributes:nil error:nil];
    if(isCreate)
        NSLog(@"YES");
    else {
        NSLog(@"NO");
    }
}
//在documnet根目录下删除文件夹
- (void)deleteFloderInDocument:(NSString*)folderName
{
    NSString *filePath =[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    
    
    BOOL isCreate = [[NSFileManager defaultManager] removeItemAtPath:[filePath stringByAppendingPathComponent:folderName] error:nil];
    if(isCreate)
        NSLog(@"YES");
    else {
        NSLog(@"NO");
    }
}
//在在指定路径下删除文件夹
- (void)deleteFloderInPath:(NSString*)path FolderName:(NSString*)folderName
{
    NSString *filePath =[NSHomeDirectory() stringByAppendingPathComponent:path];
    
    
    BOOL isCreate = [[NSFileManager defaultManager] removeItemAtPath:[filePath stringByAppendingPathComponent:folderName] error:nil];
    if(isCreate)
        NSLog(@"YES");
    else {
        NSLog(@"NO");
    }
}

+ (void)deleteFloderInPath:(NSString*)path FolderName:(NSString*)folderName
{
    NSString *filePath =[NSHomeDirectory() stringByAppendingPathComponent:path];
    
    
    BOOL isCreate = [[NSFileManager defaultManager] removeItemAtPath:[filePath stringByAppendingPathComponent:folderName] error:nil];
    if(isCreate)
        NSLog(@"YES");
    else {
        NSLog(@"NO");
    }
}

+ (void)deleteFileInPath:(NSString*)path FileName:(NSString*)FileName
{
    NSString *filePath =[NSHomeDirectory() stringByAppendingPathComponent:path];
    
    
    BOOL isCreate = [[NSFileManager defaultManager] removeItemAtPath:[filePath stringByAppendingPathComponent:FileName] error:nil];
    if(isCreate)
        NSLog(@"YES");
    else {
        NSLog(@"NO");
    }
}

+ (void) saveImageAsJpgFile:(UIImage *)image path:(NSString *)path fileName:(NSString *)fileName
{
    NSLog(@"准备存储");
    if (image == nil)
    {
        NSLog(@"传入无效image对象!");
        return ;
    }
    //NSString *filePath =[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/bookImages"];
    //filePath = [filePath stringByAppendingPathComponent:dirPath];
    NSString *filePath =[NSHomeDirectory() stringByAppendingPathComponent:path];
   
    
    if (fileName == nil)
    {
        NSLog(@"不存在文件名");
        return ;
    }
    
    [[NSFileManager defaultManager] createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    
    filePath = [filePath stringByAppendingPathComponent:fileName];
    //filePath = [filePath stringByAppendingString:@".jpg"];
    
    //NSLog(filePath);
    [UIImageJPEGRepresentation(image, 1.0) writeToFile:filePath atomically:YES];  
    
}

//从url中获得文件名
+ (NSString*)getFileNameFormUrl:(NSString*)urlStr
{
    // NSString *string1 = @"http://files.cnblogs.com/zhuqil/33UIWebViewDemo.zip44";
    int strlength=urlStr.length;
    int j;
    for(int i=0;i<strlength;i++)
    {
        char c = [urlStr characterAtIndex:i];
        if(c=='/')
            j=i+1;
        
    }
    NSLog(@"%@",[urlStr substringFromIndex:j]);
    return [urlStr substringFromIndex:j];
}
- (NSMutableArray*)getAllPhotosWithPath:(NSString*)pathString
{
    
    NSString *filePath =[NSHomeDirectory() stringByAppendingPathComponent:pathString];
    NSLog(@"the filePath is = %@",filePath);
    NSError *error = nil;
    NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:filePath error:&error];
    NSMutableArray *fileNames=[[NSMutableArray alloc]init];
    NSLog(@"%@", dirContents);
    if ( ! error) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self ENDSWITH[cd] '.jpg'"];
        NSArray *imagesOnly = [dirContents filteredArrayUsingPredicate:predicate];
        
        fileNames = [NSMutableArray arrayWithArray:imagesOnly];
    }
    //NSLog(@"photos count is=%d",[fileNames count]);
    // count = [fileNames count];  //得到数量多少
    return fileNames;
}
@end
